package com.atguigu.dga230301.meta.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.dga230301.meta.bean.TableMetaInfo;
import com.atguigu.dga230301.meta.bean.TableMetaInfoExtra;
import com.atguigu.dga230301.meta.bean.TableMetaInfoForQuery;
import com.atguigu.dga230301.meta.bean.TableMetaInfoVO;
import com.atguigu.dga230301.meta.service.TableMetaInfoExtraService;
import com.atguigu.dga230301.meta.service.TableMetaInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 元数据表 前端控制器
 * </p>
 *
 * @author zhangjunyi
 * @since 2023-06-30
 */
@RestController
@RequestMapping("/tableMetaInfo")
public class TableMetaInfoController {

    @Autowired
    TableMetaInfoService tableMetaInfoService;

    @Autowired
    TableMetaInfoExtraService tableMetaInfoExtraService;

    @GetMapping("/table-list")
    public String tableList(TableMetaInfoForQuery tableMetaInfoForQuery) {
        List<TableMetaInfoVO> tableMetaInfoList = tableMetaInfoService.getTableMetaInfoList(tableMetaInfoForQuery);

        Integer total = tableMetaInfoService.getTableMetaInfoCount(tableMetaInfoForQuery);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("total", total);
        jsonObject.put("list", tableMetaInfoList);

        return jsonObject.toJSONString();
    }

    //手动更新元数据
    @PostMapping("/init-tables/{schemaName}/{assessDate}")
    public String initTables(@PathVariable("schemaName") String schemaName, @PathVariable("assessDate") String assessDate) {
        tableMetaInfoService.initMetaInfo(assessDate, schemaName);
        return "success";
    }


    @GetMapping("/table/{id}")
    public String tableDetail(@PathVariable("id") String id) {
        //1.根据id查询到tableMetaInfo数据
//        TableMetaInfo tableMetaInfo = tableMetaInfoService.getOne(new QueryWrapper<TableMetaInfo>().eq("id", id));
        TableMetaInfo tableMetaInfo = tableMetaInfoService.getById(id);

        //2.再查询到这个tableMetaInfo对应的辅助信息数据
        TableMetaInfoExtra metaInfoExtra = tableMetaInfoExtraService.getOne(new QueryWrapper<TableMetaInfoExtra>().eq("schema_name", tableMetaInfo.getSchemaName()).eq("table_name", tableMetaInfo.getTableName()));

        //3.将辅助信息数据封装到TableMetaInfo对象中
        tableMetaInfo.setTableMetaInfoExtra(metaInfoExtra);

        //4.将数据转为JSON字符串返回
        return JSON.toJSONString(tableMetaInfo);
    }

//    @PostMapping("/tableExtra")
    public String updataTableExtra(@RequestBody TableMetaInfoExtra tableMetaInfoExtra) {
        //设置更新时间
        tableMetaInfoExtra.setUpdateTime(new Date());
        tableMetaInfoExtraService.saveOrUpdate(tableMetaInfoExtra);
        return "success";
    }
}
